﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;

namespace Remember
{
    public class NotesManager
    {
        private static string path = Directory.GetCurrentDirectory() + "/data.xml";
        private XDocument Notes;

        public NotesManager()
        {
            Notes = XDocument.Load(path);
        }

        public List<Note> GetUpcomingNotes()
        {
            List<Note> notes = new List<Note>();

            var xnotes = from n in Notes.Descendants("note")
                        select n;

            xnotes = xnotes.Where(n => (DateTime.Compare(DateTime.Parse(n.Element("expirydate").Value), DateTime.Now)) == 1 || 
                    (DateTime.Compare(DateTime.Parse(n.Element("expirydate").Value), DateTime.Now)) == 0);

            foreach (var n in xnotes)
            {
                notes.Add(Note.Create(n));
                Debug.Write(n.Element("id").Value);
            }

            return notes;
        }

        public List<Note> GetPassedMotes()
        {
            List<Note> notes = new List<Note>();

            var xnotes = from n in Notes.Descendants("note")
                         select n;

            xnotes = xnotes.Where(n => (DateTime.Compare(DateTime.Parse(n.Element("expirydate").Value), DateTime.Now)) == - 1);

            foreach (var n in xnotes)
            {
                notes.Add(Note.Create(n));
                Debug.Write(n.Element("id").Value);
            }

            return notes;
        }

        public bool AddNote(Note note)
        {
            Note anote = note;

            var xid = from i in Notes.Descendants().Elements("lastid")
                      select i;
            int id = int.Parse(xid.Single().Value);

            anote.ID = id;

            Notes.Root.AddFirst(note.XML());
            xid.Single().SetValue(id + 1);
            Notes.Save(path);

            return true;
        }
    }
}
